package com.guigu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.mapper.OrdersParticularsMapper;
import com.guigu.mapper.ReturnShopInfoMapper;
import com.guigu.mapper.*;
import com.guigu.pojo.*;
import com.guigu.service.OrdersParticularsService;
import com.guigu.service.OrdersService;
import com.guigu.service.ReturnCaseService;
import com.guigu.service.ReturnShopInfoService;
import com.guigu.service.utils.MyIdAdd;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;



@Service
public class ReturnShopInfoServiceimpl extends ServiceImpl<ReturnShopInfoMapper, ReturnShopInfo> implements ReturnShopInfoService {

    @Autowired
    ReturnShopInfoMapper returnShopInfoMapper;

    @Autowired
    OrdersParticularsService detailService;

    @Autowired
    MyIdAdd myIdAdd;

    @Autowired
    ReturnCaseService returnCaseService;

    @Autowired
    ReturnCaseService caseService; //退货原因

    @Autowired
    OrdersService orderService;//订单Service

    @Autowired
    OrdersParticularsMapper ordersParticularsMapper;
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    CompanyRunningWaterMapper companyRunningWaterMapper;
    @Autowired
    UsersMapper usersMapper;
    @Override
    //根据订单详情id去查询退货申请表
    public Page<ReturnShopInfo> queryAllreturn(ReturnShopInfo returnShopInfo, Integer pageno, Integer pagesize) {
        QueryWrapper<ReturnShopInfo> queryWrapper = new QueryWrapper<ReturnShopInfo>();
        queryWrapper.select().orderByDesc("return_time");
        //退货单号
        if( StringUtils.isNotBlank(returnShopInfo.getReturnNumber())){
            queryWrapper.like("return_number", returnShopInfo.getReturnNumber());
        }
        //订单详情id
        if( returnShopInfo.getOdId()!=null){
            queryWrapper.eq("od_id", returnShopInfo.getOdId());
        }
        //退货人
        if (returnShopInfo.getUid()!=null){
            queryWrapper.eq("uid", returnShopInfo.getUid());
        }
        //是否审核
        if(returnShopInfo.getIsAudit()!=null){
            queryWrapper.eq("is_audit", returnShopInfo.getIsAudit());
        }
        //货物状态
        if(returnShopInfo.getShopState()!=null){
            queryWrapper.eq("shop_state", returnShopInfo.getShopState());
        }
        //是否删除
        if(returnShopInfo.getIsDelete()!=null){
            queryWrapper.eq("is_delete", returnShopInfo.getIsDelete());
        }
        //是否设计过
        if(returnShopInfo.getIsDesign()!=null){
            queryWrapper.eq("is_design", returnShopInfo.getIsDesign());
        }
        Page<ReturnShopInfo> page = this.page(new Page<ReturnShopInfo>(pageno, pagesize), queryWrapper);
        //循环组装数据
        for (ReturnShopInfo r : page.getRecords()) {
            List<String> list = new ArrayList<>();
            if (r.getReturnImg1() != null) {
                r.setReturnImg1("http://127.0.0.1:9090/demo/" + r.getReturnImg1());
                list.add(r.getReturnImg1());
            }
            if (r.getReturnImg2() != null) {
                r.setReturnImg2("http://127.0.0.1:9090/demo/" + r.getReturnImg2());
                list.add(r.getReturnImg2());
            }
            if (r.getReturnImg3() != null) {
                r.setReturnImg3("http://127.0.0.1:9090/demo/" + r.getReturnImg3());
                list.add(r.getReturnImg3());
            }
            r.setSrcList(list.toArray(new String[]{}));
            r.setReturnCase(caseService.getById(r.getRefundCaseid()));
            r.setDetail(detailService.queryDeatilById(r.getOdId()));
        }
        return page;
    }

    @Override
    public Map addRefundShopByDetailId(ReturnShopInfo refund) {
        return null;
    }

    //根据订单详情添加退货表
    @Override
    @Transactional
    public Map addRefundShopByDetailId(ReturnShopInfo refund, MultipartFile[] imgs, HttpServletRequest request) {
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "提交失败");
        refund.setReturnNumber(myIdAdd.idadd("400",true));
        refund.setReturnTime(new Date());
        refund.setIsAudit(0);
        refund.setGoodsState(0);
        refund.setIsDelete(0);
        refund.setIsDesign(0);
        List<String> urls = new ArrayList<String>();
        for (MultipartFile img : imgs) {
            if (img.getSize() > 0) {
                String apppath = request.getServletContext().getRealPath("/imags"); //路径名
                File file = new File(apppath);
                if (!file.exists()) {
                    //不存在就创建
                    file.mkdirs();
                }
                //获取文件名称
                String fileName = img.getOriginalFilename();
                //保存文件到路径
                try {
                    img.transferTo(new File(apppath, fileName));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //将路径设置到集合中
                urls.add("imags/" + fileName);
            }
        }
        //组装路径
        if (urls.size() > 0) {
            refund.setReturnImg1(urls.get(0));
        }
        if (urls.size()>1){
            refund.setReturnImg2(urls.get(1));
        }
        if (urls.size()>2){
            refund.setReturnImg3(urls.get(2));
        }
        //检查本次申请的当前货物状态
        if(refund.getShopState()==0){
            //用户未收到货物
            //获取订单详情对象
            OrdersParticulars ordersParticulars=ordersParticularsMapper.selectById(refund.getOdId());
            //获取订单对象
            Orders orders=orderService.getById(ordersParticulars.getPId());
            //检查商户是否确认收货
            if (orders.getGoodsState().equals("g-4")){
                //商户收到货物，说明是商户确认收货时，用户拒绝收货,发起退货申请
                refund.setGoodsState(9);
            }else
            {
                //商户未收到货物，说明是仅退款
                refund.setGoodsState(5);
            }
        }else {
            //用户收到货物，说明是退货退款
            refund.setGoodsState(1);
        }
        boolean b = this.save(refund);
        if (b) {
            //修改订单详情表状态
            OrdersParticulars detail=new OrdersParticulars();
            detail.setId(refund.getOdId());
            detail.setIsReturn(1);
            detailService.updateById(detail);
            map.put("code", 1);
            map.put("msg", "提交成功,请等待退款");
        }
        return map;
    }

    @Override
    public ReturnShopInfo queryBYid(Integer id) {
        QueryWrapper<ReturnShopInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("od_id",id);
        return this.getOne(queryWrapper);
    }
    //曹科 退货根据页面按钮来修改状态
    @Override
    public Map updatereturns(ReturnShopInfo returnShopInfo) {
        Map map=new HashMap();
        map.put("code",0);
        map.put("msg","确认退货失败");
        if(returnShopInfo.getId()!=null && returnShopInfo.getGoodsState()!=null){
            boolean b=this.updateById(returnShopInfo);
            if(b){
                map.put("code",1);
                map.put("msg","确认退货成功");
            }
        }
        return map;
    }

    //退货申请单编号
    @Override
    public List<String> getIds(String str) {
        List<String> list = new ArrayList<String>();
        QueryWrapper<ReturnShopInfo> queryWrapper = new QueryWrapper<ReturnShopInfo>();
        queryWrapper.likeRight("return_number", str);
        List<ReturnShopInfo> tempList = this.list(queryWrapper);
        for (ReturnShopInfo obj : tempList) {
            list.add(obj.getReturnNumber());
        }
        return list;
    }

    //根退货表id查询申请退货对象
    @Override
    public ReturnShopInfo queryRefundByDetailId(Integer id) {
        ReturnShopInfo one = this.getById(id);
        if (one != null) {
            one.setReturnCase(caseService.getById(one.getRefundCaseid()));
            one.setDetail(detailService.queryDeatilById(id));
        }
        return one;
    }

    //审核退货申请
    @Override
    public Map ckRefund(ReturnShopInfo refund) {
        //商户A： 600
//        订单A 300;
//        订单B 300;
//        仓库A：500;订单A取走300，订单B取走200个，还差100个
//        仓库B：100;订单B取走100，
//        结果：订单A指定仓库A，订单B指定仓库？

        //那么应该是出库失败，显示当前添加的所有出库表和出库详情信息(需要显示指定哪个仓库)【在删除之前保存到map对应的value中返回集合】
        //如下：
        //订单A
        //详情：从仓库A取走300个。√
        //订单B
        //详情：从仓库A取走200个，还差100个，库存不足，中断出库申请。【提示需要进行仓库间调度】×
        //提示调度

        //总共供应商品的数量
        //            //正在供应的商品数量
        //            //停止供应的商品数量
        //            //本月供应的商品总数

        Map map = new HashMap();
        Integer audit=refund.getIsAudit();
        //进行修改
        if(this.updateById(refund)){
            //补全属性
            refund=returnShopInfoMapper.selectById(refund.getId());
            refund.setIsAudit(audit);
            //允许通过
            map.put("msg","允许通过！");
            map.put("x",true);
            //检查本次申请的当前货物状态
            if(refund.getShopState()==0){
                //用户未收到货物，说明是仅退款
                refund.setGoodsState(5);
            }else {
                //用户收到货物，说明是退货退款
                refund.setGoodsState(1);
            }
            //进行修改
            returnShopInfoMapper.updateById(refund);
        }else {
            map.put("msg","操作错误");
            map.put("x",false);
        }
        return map;
    }

    //签收退货单
    @Override
    public Map receiptForReturn(ReturnShopInfo refund) {
        Map map=new HashMap<String,Object>();
        //直接进行修改
        if(returnShopInfoMapper.updateById(refund)>0){
            map.put("msg","签收成功【已将退货金额返回给用户】，等待入库");
            map.put("x",true);

            //根据退货申请表id，获取退货申请表对象
            refund=returnShopInfoMapper.selectById(refund.getId());
            //根据订单详情id，获取订单详情对象
            OrdersParticulars ordersParticulars=ordersParticularsMapper.selectById(refund.getOdId());
            //获取订单对象
            Orders orders=ordersMapper.selectById(ordersParticulars.getPId());
            //获取用户
            Users users=usersMapper.selectById(orders.getUId());
            //退款之后的用户额度=当前余额+退货余额
            users.setBalance(users.getBalance()+refund.getMoney());
            usersMapper.updateById(users);
            //添加一条流水表
            CompanyRunningWater companyRunningWater=new CompanyRunningWater();
            //流水编号
            companyRunningWater.setPipelineId(myIdAdd.idadd("500",true));
            //付钱用户id
            companyRunningWater.setAccountId(10);
            //收钱用户id
            companyRunningWater.setUid(users.getId());
            //账单编号【这里取退货申请单编号】
            companyRunningWater.setOid(refund.getReturnNumber());
            //流水金额
            companyRunningWater.setRmoney(refund.getMoney());
            //流水日期
            companyRunningWater.setRdate(new Date());
            //流水类型【订单退款】
            companyRunningWater.setRtype(2);
            //删除状态
            companyRunningWater.setIsDelete(0);
            //进行添加
            companyRunningWaterMapper.insert(companyRunningWater);
        }else{
            map.put("msg","操作错误");
            map.put("x",false);
        }
        return map;
    }
}
